<?php
/****
	观察者模式
****/
header('Content-type:text/html;charset=utf-8');

//PHP实现观察者
//php5中提供观测者observer与被观察者subject的接口

class User implements SplSubject{ 
	public $login_num;
	public $fancy;

	protected $observers = null;

	public function __construct($fancy){
		$this->login_num = rand(1,10);
		$this->fancy = $fancy;
		$this->observers = new SplObjectStorage();
	}

	public function login(){
		$this->notify();
	}

	public function attach(SplObserver $observer){
		$this->observers->attach($observer);
	}

	//取消关注
	public  function detach(SplObserver $observer){
		$this->observers->detach($observer);
	}

	//通知
	public  function notify(){
		$this->observers->rewind();
		while($this->observers->valid()){
			$observer = $this->observers->current();
			$observer->update($this);//更新方法
			$this->observers->next();
		}
	}
}

// Receive update from subject
class Secrity implements SplObserver{
	public function update(SplSubject $subject){
		if($subject->login_num < 3){
			echo "这是第".$subject->login_num."次安全登录<br/>";
		}else{
			echo "这是第".$subject->login_num."次登录,登录异常<br/>";//输出浏览器是用br,文件使用\r\n
		}	
	}
}

class Ad implements SplObserver{
	public function update(SplSubject $subject){
		if($subject->fancy == 'sports'){
			echo "足球比赛预定<br/>";
		}else{
			echo "好好学习<br/>";
		}
	}
}


$user = new User('sports');
$user->attach(new Secrity());
$user->login();